import java.util.HashMap;
import java.util.Map;

/**
 * @author hewei
 * @version 1.0
 * @description: 1007. 行相等的最少多米诺旋转
 * @date 2022/10/27 14:58
 */

public class MinDominoRotations {

    public int minDominoRotations1(int[] tops, int[] bottoms) {
        HashMap<Integer, Integer> count = new HashMap<>();
        HashMap<Integer, Integer> map = new HashMap<>();
        int n = tops.length;
        for (int i = 0; i < n; i++) {
            int top = tops[i];
            int bottom = bottoms[i];
            if (top != bottom) {
                count.put(top, count.getOrDefault(top, 0) + 1);
            }
            count.put(bottom, count.getOrDefault(bottom, 0) + 1);
            map.put(top, map.getOrDefault(top, 0) + 1);
            map.put(bottom, map.getOrDefault(-bottom, 0) + 1);
        }
        int ans = 0;
        boolean flag = false;
        for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
            if (entry.getValue() == n) {
                flag = true;
                ans = Math.max(ans, Math.abs(map.get(entry.getKey())));
                ans = Math.max(ans, Math.abs(map.get(-entry.getKey())));
            }
        }
        return flag ? n - ans : -1;
    }

    public int minDominoRotations(int[] tops, int[] bottoms) {
        int res = process(tops[0], tops, bottoms);
        if (res != -1) return res;
        return process(bottoms[0], tops, bottoms);
    }

    public int process(int target, int[] tops, int[] bottoms) {
        int top = 0;
        int bottom = 0;
        for (int i = 0; i < tops.length; i++) {
            if (tops[i] == target || bottoms[i] == target) {
                if (tops[i] == target) ++top;
                if (bottoms[i] == target) ++bottom;
            } else return -1;
        }
        return tops.length - Math.max(top, bottom);
    }
}
